import LangImg from "../ccExt/LangImg";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('GlobalUI/MutiLanguageImg')
export default class MutiLanguageImg extends cc.Component {

    @property
    private readonly key: string = "";

    protected onLoad(): void {
        this.fetchRender();
        yy.event.on(this, yy.event.lang.LanuageChanged, this.updateSprite);
    }

    protected onEnable(): void {
        this.updateSprite();
    }

    private fetchRender() {
        this._sprite = this.getComponent(cc.Sprite);
        if (!this._sprite)
            this._sprite = this.getComponent(cc.Mask);
    }
    private _sprite: cc.Sprite | cc.Mask = null;

    private updateSprite() {
        if (!this._sprite || !this._sprite.isValid || !this.node.activeInHierarchy) return;
        // 逻辑优化，未查询到的资源不替换，使用项目默认语言资源；并输出警告日志。
        const spriteFrame = LangImg.getIns().getIcon(this.key);
        if (spriteFrame)
            this._sprite.spriteFrame = spriteFrame;
        else
            cc.warn(`当前图片多语言库未收录资源：${this.key}`);
    }
}
